const moment = require('moment');
moment.locale('zh-cn');

module.exports = {
  /**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 * @param {*} rootId 根Id 默认 0
 */
  async handleTree(data = [], id = "id", parentId = "parentId", children = "children", rootId = 0) {
    id = id || 'id'
    parentId = parentId || 'parentId'
    children = children || 'children'
    rootId = rootId || 0
    //对源数据深度克隆
    const cloneData = JSON.parse(JSON.stringify(data))
    //循环所有项
    const treeData = cloneData.filter(father => {
      let branchArr = cloneData.filter(child => {
        //返回每一项的子级数组
        return father[id] === child[parentId]
      });
      branchArr.length > 0 ? father.children = branchArr : '';
      //返回第一层
      return father[parentId] === rootId;
    });
    return treeData != '' ? treeData : data;
  },
  /**
   * 格式化返回数据
   * @param {number} code 状态码
   * @param {string} msg 返回信息
   * @param {*} data 返回数据
   */
  formateResponse(data,code=200,msg="操作成功"){
    return {
      code,
      msg,
      data
    }
  },
  formateResponseList(data,code=200,msg="操作成功"){
    return {
      code,
      msg,
      rows:data.rows,
      total:data.count
    }
  },
  // 格式化参数
  formatOptions(params={},arr=[]){
    const {app} = this;
    const {Op} = app.Sequelize;
    let option = {
      where:{}
    };
    if(params.pageSize) option.limit = Number(params.pageSize);
    if(params.pageNum) option.offset = Number(params.pageSize*(params.pageNum - 1));
    if(params.ids) option.where.id = {[Op.in]: params.ids.split(',')};
    arr.forEach(key=>{
      if(params[key]){
        option.where[key] = {
          [Op.like]:"%"+params[key]+"%"
        }
      }
    });
    if(params["params[beginTime]"] && params["params[endTime]"]){
      option.where.created_at = {
        [Op.between]:[moment(params["params[beginTime]"]),moment(params["params[endTime]"])]
      };
    }
    if(params.beginTime && params.endTime){
      option.where.create_at = {
        [Op.between]:[moment(params.beginTime),moment(params.endTime)]
      };
    }
    return option;
  },
  /**
   * 下滑线转驼峰
   * @param {string} name 下划线属性名
   */
  toHump(name){
    return name.replace(/\_(\w)/g,(all,letter)=>{
      return letter.toUpperCase();
    })
  },
  /**
   * 驼峰转下划线
   * @param {string} name 驼峰属性名
   * @returns 
   */
  toLine(name){
    return name.replace(/([A-Z])/g,"_$1").toLowerCase();
  }
}